package com.app.aop;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpStatus;
import com.app.utils.R;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.omg.CORBA.TRANSACTION_MODE;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@Aspect
public class UserAop {
//    @Pointcut("within(com.app.controller.*) && @annotation(com.app.aop.ParamNotNull)")
//    public void pointCut(){}

    @Around("@annotation(bodyParamNotNull)")
    public Object around(ProceedingJoinPoint pjp, BodyParamNotNull bodyParamNotNull){
        Object[] args = pjp.getArgs();
        try {
            for (Object param:args){
                if (ObjectUtil.isEmpty(param)) return R.error("参数错误");
            }
            try {
                String[] paramNames = bodyParamNotNull.params();
                Object obj= args[bodyParamNotNull.index()];
                if (obj.getClass().getName().contains("Map")){
                    for (String name:paramNames){
                        if (ObjectUtil.isEmpty(((Map<String,Object>)obj).get(name)))
                            return R.error("参数错误");
                    }
                }
            }catch (Exception ignored){
                System.out.println("参数检查失败");
                return R.error("参数检查失败");
            }
            return pjp.proceed(args);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            return R.error(HttpStatus.HTTP_INTERNAL_ERROR,"系统执行期间发送错误,可能是参数问题");
        }
    }
}
